package com.loren.demo03.tcp1.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

public class TcpSocketServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) {
        String message = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
        if ("HeartbeatCheck".equals(message)) {
            context.channel().eventLoop().execute(() -> context.writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8)));
        } else {
            System.out.println("message = " + message);
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext context) {
        Channel channel = context.channel();
        System.out.println("TCP 客户端连接 -> id = " + channel.id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext context) {
        Channel channel = context.channel();
        System.out.println("TCP 客户端移除 -> id = " + channel.id().asLongText());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext context, Object event) throws Exception {
        if (event instanceof IdleStateEvent) { // 心跳检查，如果发生读空闲，则关闭通道
            IdleStateEvent stateEvent = (IdleStateEvent) event;
            if (stateEvent.state() == IdleState.READER_IDLE) {
                context.channel().close();
            }
        } else {
            super.userEventTriggered(context, event);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
        context.close();
    }
}
